def periodic_transposition_encrypt(plaintext, key):
    """
    周期换位加密（按密钥字母顺序排列列）
    :param plaintext: 明文字符串
    :param key: 密钥字符串（如"CAT"）
    :return: 密文
    """
    plaintext = plaintext.replace(" ", "").upper()
    key = key.upper()

    # 检查密钥有效性
    if len(set(key)) != len(key):
        raise ValueError("密钥不能包含重复字符")  # 
    m = len(key)
    if m == 0:
        raise ValueError("密钥不能为空")

    # 生成列顺序（按字母升序排列） 
    sorted_key = sorted(key)
    key_order = [key.index(c) for c in sorted_key]

    # 填充处理 [[10]]
    padding_length = (m - len(plaintext) % m) % m
    plaintext += 'X' * padding_length

    # 分组加密 
    groups = [plaintext[i:i + m] for i in range(0, len(plaintext), m)]
    ciphertext = []
    for group in groups:
        encrypted_group = ''.join([group[i] for i in key_order])
        ciphertext.append(encrypted_group)
    return ''.join(ciphertext)


def periodic_transposition_decrypt(ciphertext, key):
    """
    周期换位解密
    :param ciphertext: 密文字符串
    :param key: 加密时使用的密钥字符串
    :return: 明文（可能含填充X）
    """
    ciphertext = ciphertext.upper()
    key = key.upper()

    # 验证密钥有效性
    if len(set(key)) != len(key):
        raise ValueError("密钥不能包含重复字符")
    m = len(key)
    if m == 0 or len(ciphertext) % m != 0:
        raise ValueError("密文长度必须是密钥长度的整数倍")

    # 生成逆置换顺序 
    sorted_key = sorted(key)
    key_order = [key.index(c) for c in sorted_key]
    inverse_order = [0] * m
    for new_idx, orig_idx in enumerate(key_order):
        inverse_order[orig_idx] = new_idx

    # 分组解密 
    groups = [ciphertext[i:i + m] for i in range(0, len(ciphertext), m)]
    plaintext = []
    for group in groups:
        decrypted_group = ''.join([group[i] for i in inverse_order])
        plaintext.append(decrypted_group)
    return ''.join(plaintext).rstrip('X')


# 使用示例 
if __name__ == "__main__":
    key = "CAT"  # 列顺序：A(1)→C(0)→T(2)
    message = "HELLOWORLD"

    encrypted = periodic_transposition_encrypt(message, key)
    print(f"加密结果: {encrypted}")  # 输出：EHLOWLROXDX

    decrypted = periodic_transposition_decrypt(encrypted, key)
    print(f"解密结果: {decrypted}")  # 输出：HELLOWORLD